$(function() {

    //获取下拉框里的值
    // $("select").find("option:selected").val();

    //动态改变下拉框 用JSON
    async function getSubject() {
        let subject = await jqAjax("GET", "/static/data/subject.json")
        console.log('动态JSON:' + subject.subject);
        var option = subject.subject;
        //渲染到页面
        for (var i = 0; i < subject.subject.length; i++) {
            $("select").prepend('<option>' + option[i].name + '</option>');
        }
    }
    getSubject();

    //获取点击单选框的值
    //$("input[name='questionType']:checked").val()

    //判断是否有文件
    $("button").on("click", function() {
        if ($("#file").prop("files").length <= 0) {
            alert('请选择文件');
        }
    })

    //点击提交上传数据
    $("button").on("click", function() {
        console.log('学科类型: ' + $("select").find("option:selected").val());
        async function insertData() {
            var fd = new FormData();
            fd.append("img", $("#file").prop("files")[0]);
            var imgUrl;
            $.ajax({
                type: 'POST',
                url: 'http://www.liulongbin.top:3006/api/upload/avatar', //
                data: fd,
                contentType: false,
                processData: false,
                async: false,
                success: function(data) {
                    if (data.status == 200) {
                        console.log('成功上传文件');
                        imgUrl = 'http://www.liulongbin.top:3006' + data.url
                        $(".img").show()
                        $('img').prop('src', imgUrl)

                    } else {
                        console.log('失败');
                    }
                },
                error: function(xhr, status, error) {
                    console.log('error');
                    console.log(xhr);
                    console.log(status);
                    console.log(error);
                }
            })
            try {
                let data = await jqAjax("POST", "/questions/", JSON.stringify({
                    direction: $("select").find("option:selected").val(),
                    options: [{
                        code: "a",
                        img: imgUrl,
                        title: "title",
                        isRight: "0"
                    }],
                    questionType: $("input[name='questionType']:checked").val()
                }))
            } catch (error) {
                console.log("catch出错");
                console.log(error);
            }
        }
        debounce(insertData(), 500)


    })

})